<?php


namespace App\Http\Middleware;


use App\Exceptions\BusinessException;
use App\Services\VipService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class NeedVip
{
    public function handle(Request $request, Closure $next, $module = null)
    {
        $service = app(VipService::class);

        if ($module && $service->isNeedVipByRouteName($module, Route::currentRouteName())) {
            $memberId = auth('api')->user()->id ?? 0;
            if (!$memberId) {
                return response()->json(['code' => 40001, 'message' => '未登录', 'data' => []], 401);
            }

            try {
                $ret = $service->checkMemberVip($memberId);

                if (!$ret) {
                    return response()->json(['code' => 41000, 'message' => '此内容需vip才能浏览', 'data' => []], 400);
                }
            } catch (BusinessException $e) {
                if ($e->getCode() == 40001) {
                    return response()->json(['code' => 40001, 'message' => '未登录', 'data' => []], 401);
                }

                return response()->json(['code' => -1, 'message' => $e->getMessage(), 'data' => []], 400);
            }
        }

        return $next($request);
    }
}
